package com.tenement.controller.foreground.user;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tenement.base.constants.SysmConstants.state;
import com.tenement.base.exception.ParameterException;
import com.tenement.mybatis.entity.User;
import com.tenement.service.interfaces.IUserService;

/**
 * 用户登录Controller
 * 
 * @author wk
 *
 */
@Controller
public class UserLoginController {

	private static final Log logger = LogFactory.getLog(UserLoginController.class);

	@Autowired
	private IUserService iUserService;

	private String pageFlag = "000";// 页面标记，如果在房源详情页面点击登录，登录之后则返回之前的页面window.history.go(-1)

	/**
	 * 进入用户登录页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user_login.action")
	public String toUserLoginHtml(String pageType) {
		try {
			if (pageType == null || "".equals(pageType)) {
				throw new ParameterException("【登录功能-页面标记pageType参数为空】");
			} else if ("houseDetail".equals(pageType)) {
				pageFlag = "111";// 表示详情页面标记
			} else {
				pageFlag = "000";
			}
		} catch (ParameterException p) {
			p.printStackTrace();
		}
		logger.info("【-进入用户登录页面-】");
		return "redirect:view/foreground/user/user_login.html";
	}

	/**
	 * 用户登录，通过手机号或邮箱进行登录，登录成功后把用户信息存储到session中，
	 * 
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login.action")
	public @ResponseBody JSONObject userLogin(@RequestBody String data, HttpServletRequest request) {
		logger.info("【-请求成功-】" + data);
		User user = new User();
		JSONObject jsonstr = JSON.parseObject(data);
		String account = jsonstr.getString("account"); // 用户账号
		String password = jsonstr.getString("password");// 用户密码
		logger.info("【-account-】" + account + "【-passoword-】" + password);
		user.setuPassword(password);
		// 判断是邮箱还是手机号的正则表达式
		String emailReg = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
		// String phoneReg = "^[1][34578]\\d{9}$";
		String flag;
		JSONObject jsonObject = new JSONObject();
		if (account.matches(emailReg)) {
			user.setuEmail(account);
			flag = iUserService.userLoginByEmail(user, request);
		} else {
			user.setuTelephone(account);
			flag = iUserService.userLoginByPhone(user, request);
		}
		if (state.Success.equals(flag)) {
			jsonObject.put("stateFlag", state.Success);
		} else {
			jsonObject.put("stateFlag", state.Failed);
		}
		jsonObject.put("pageFlag", pageFlag);
		return jsonObject;
	}

}
